package day01;

/*
 * Author: JacksonCoder
 * FileName: insertSort
 * Version: 1.0.0
 * Date: 2024/12/26
 */

public class insertSort {

    public static void InsertSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // 0 ~ 0 有序
        // 0 ~ 1 有序
        // 0 ~ 2 有序
        int N = arr.length;
        for (int end = 1; end < N; end++) {
            int newNumIndex = end;
            while (newNumIndex - 1 >= 0 && arr[newNumIndex - 1] > arr[newNumIndex]) {
                swap(arr, newNumIndex - 1, newNumIndex);
                newNumIndex--;
            }
        }
    }

    public static void insertSort2(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        int N = arr.length;
        for (int end = 1; end < N; end++) {
            // pre 新数的前一个位置  end - 1    end
            for (int pre = end - 1; pre >= 0 && arr[pre] > arr[pre + 1]; pre--) {
                swap(arr, pre, pre + 1);
            }
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void printArray(int[] arr) {
        for (int a : arr) {
            System.out.print(a + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 4, 2, 0, 9, 7, 1, 6};
        printArray(arr);
        InsertSort(arr);
        printArray(arr);
        int[] arr2 = {5, 3, 8, 4, 2, 0, 9, 7, 1, 6};
        printArray(arr2);
        insertSort2(arr2);
        printArray(arr2);
    }

}
